<template>
  <el-card>
    <el-form
      ref="searchForm"
      :inline="true"
      :model="searchFormModel"
      label-width="undefined"
      size="small"
      @submit.prevent>
      <el-form-item :label="$t('forms.processKey')" prop="value">
        <el-input
          v-model="searchFormModel.processKey"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + $t('forms.processKey')"
          @keyup.enter="handleSearch" />
      </el-form-item>
      <el-form-item :label="$t('forms.name')" prop="value">
        <el-input
          v-model="searchFormModel.name"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + $t('forms.name')"
          @keyup.enter="handleSearch" />
      </el-form-item>
      <el-form-item style="float: right">
        <el-button-group>
          <el-button :loading="modal_loading" type="primary" @click="handleSearch">
            {{ $t('forms.buttons.search') }}
          </el-button>
          <el-button :loading="modal_loading" type="primary" @click="handleSearchReset">
            {{ $t('forms.buttons.reset') }}
          </el-button>
          <el-button :loading="modal_loading" type="primary" @click="handleAdd">
            {{ $t('forms.buttons.add') }}
          </el-button>
          <el-button :loading="modal_loading" type="primary" @click="handleDeleteMore">
            {{ $t('forms.buttons.delete') }}
          </el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
    <el-table
      ref="table"
      v-loading="modal_loading"
      :data="searchData"
      :default-sort="searchFormModel.orderParam"
      :empty-text="$t('messages.tableNoData')"
      :height="tableHeight"
      border
      header-cell-class-name="query-table-header"
      size="small"
      @row-click="handleRowClick"
      @selection-change="handleSelect"
      @sort-change="handleSortChange">
      <el-table-column align="center" fixed="left" type="selection" width="40"></el-table-column>
      <el-table-column :label="$t('forms.processKey')" prop="processKey" sortable="custom">
      </el-table-column>
      <el-table-column :label="$t('forms.name')" prop="name" sortable="custom"></el-table-column>
      <el-table-column :label="$t('forms.version')" prop="version" sortable="custom" width="80">
      </el-table-column>
      <el-table-column :label="$t('forms.remarks')" prop="remarks"></el-table-column>
      <el-table-column
        :label="$t('forms.createTime')"
        prop="createTime"
        sortable="custom"
        width="140">
        <template #default="scope">
          <span>{{ dateTimeFormat(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('forms.modifyTime')"
        prop="modifyTime"
        sortable="custom"
        width="140">
        <template #default="scope">
          <span>{{ dateTimeFormat(scope.row.modifyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('forms.deployTime')"
        prop="deployTime"
        sortable="custom"
        width="140">
        <template #default="scope">
          <span>{{ dateTimeFormat(scope.row.deployTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :fixed="isMobile ? false : 'right'"
        :label="$t('forms.action')"
        align="center"
        prop="action"
        width="90">
        <template #default="scope">
          <el-button icon="el-icon-edit" link type="primary" @click="handleEdit(scope.row)" />
          <el-button
            icon="el-icon-delete"
            link
            type="primary"
            @click="handleDeleteRow(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="searchFormModel.currPage"
      v-model:page-size="searchFormModel.pageSize"
      :layout="isMobile ? 'prev, pager, next' : 'total, sizes, prev, pager, next, jumper'"
      :page-sizes="searchFormModel.pageSizeArray"
      :size="isMobile?'small':'default'"
      :total="searchFormModel.totalRows"
      @size-change="handlePageSizeSearch">
    </el-pagination>
    <el-dialog
      v-model="editModal"
      :close-on-click-modal="false"
      :fullscreen="isMobile"
      :title="$t('forms.info')">
      <el-form
        ref="editForm"
        v-loading="modal_loading"
        :model="editFormModel"
        :rules="ruleValidate"
        label-width="undefined"
        size="small"
        style="padding-right: 25px"
        @submit.prevent>
        <div v-if="this.action === 1">
          <el-form-item :label="$t('forms.processKey') + ':'" prop="processKey">
            <span>{{ editFormModel.processKey }}</span>
          </el-form-item>
          <el-form-item :label="$t('forms.name') + ':'" prop="name">
            <span>{{ editFormModel.name }}</span>
          </el-form-item>
        </div>
        <el-form-item :label="$t('forms.content') + ':'" prop="content">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleUploadBpmn">
            <el-button slot="default" type="primary" size="small" @click.stop="handleEditBpmn">
              {{
                !!editFormModel.deploymentId ? $t('forms.buttons.view') : $t('forms.buttons.edit')
              }}
            </el-button>
            <el-button
              v-if="!editFormModel.deploymentId"
              slot="trigger"
              size="small"
              type="primary">
              {{ $t('forms.buttons.upload') }}
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('forms.remarks') + ':'" prop="remarks">
          <el-input
            v-model="editFormModel.remarks"
            :disabled="modal_loading"
            :placeholder="$t('forms.pleaseEnter') + $t('forms.remarks')"
            :rows="3"
            type="textarea" />
        </el-form-item>
        <div v-if="action === 1">
          <el-form-item :label="$t('forms.version') + ':'" prop="version">
            <span>{{ editFormModel.version }}</span>
          </el-form-item>
          <el-form-item :label="$t('forms.createTime') + ':'" prop="createTime">
            <span>{{ dateTimeFormat(editFormModel.createTime) }}</span>
          </el-form-item>
          <el-form-item :label="$t('forms.modifyTime') + ':'" prop="modifyTime">
            <span>{{ dateTimeFormat(editFormModel.modifyTime) }}</span>
          </el-form-item>
          <el-form-item :label="$t('forms.deployTime') + ':'" prop="deployTime">
            <span>{{ dateTimeFormat(editFormModel.deployTime) }}</span>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button-group>
          <el-button
            v-if="action === 1"
            :loading="modal_loading"
            type="info"
            @click="handleDownLoadFile">
            {{ $t('forms.buttons.downLoadFile') }}
          </el-button>
          <el-button :loading="modal_loading" type="warning" @click="doReset">
            {{ $t('forms.buttons.reset') }}
          </el-button>
          <el-button :loading="modal_loading" type="primary" @click="handleSave">
            {{ $t('forms.buttons.save') }}
          </el-button>
          <el-button
            v-if="!!editFormModel.id && !editFormModel.deploymentId"
            :loading="modal_loading"
            type="success"
            @click="handleDeploy">
            {{ $t('forms.buttons.deploy') }}
          </el-button>
        </el-button-group>
      </template>
      <el-dialog v-model="bpmnView" :title="$t('forms.processFile')" fullscreen>
        <camunda-bpmn
          ref="bpmn"
          v-model="editFormModel.content"
          :format="true"
          :read-only="!!editFormModel.deploymentId"
          @save="handleBpmnChange" />
      </el-dialog>
    </el-dialog>
  </el-card>
</template>
<script>
import moment from 'moment'
import { copy, isMobileDevice } from '@/libs/tools'
import { nextTick, ref } from 'vue'
import CamundaBpmn from '@/plugins/camunda-bpmn'

export default {
  name: 'workflowDeploy',
  components: { CamundaBpmn },
  data() {
    return {
      searchFormModel: {
        processKey: '',
        name: '',
        orderParam: {
          prop: 'createTime',
          order: 'ascending'
        },
        currPage: 1,
        totalRows: 0,
        pageSize: 10,
        pageSizeArray: [10, 20, 30, 40]
      },
      editFormModel: {
        id: '',
        processKey: '',
        name: '',
        content: '',
        version: '',
        remarks: '',
        createTime: '',
        modifyTime: '',
        deployTime: '',
        deploymentId: ''
      },
      editModal: false,
      modal_loading: false,
      bpmnView: false,
      searchData: [],
      selectedData: [],
      action: 0,
      currObj: {}
    }
  },
  computed: {
    isMobile() {
      return isMobileDevice()
    },
    tableHeight() {
      const minHeight = 300
      const height = this.$store.state.app.mainHeight - 80 - 46 - 42 - 4
      if (height < minHeight) {
        return minHeight - 2
      } else {
        return height
      }
    },
    ruleValidate() {
      return {
        content: [
          {
            required: true,
            message: this.$i18n.t('forms.content') + this.$i18n.t('forms.notEmpty'),
            trigger: 'change'
          }
        ],
        remarks: [
          {
            required: true,
            message: this.$i18n.t('forms.remarks') + this.$i18n.t('forms.notEmpty'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    'searchFormModel.currPage'() {
      this.handleSearch()
    }
  },
  methods: {
    dateTimeFormat(time) {
      return time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    doReset() {
      nextTick(() => {
        this.editForm.resetFields()
        this.editFormModel = copy(this.currObj)
      })
    },
    clearCurrObj() {
      nextTick(() => {
        this.currObj = {
          id: '',
          processKey: '',
          name: '',
          content: '',
          version: '',
          remarks: '',
          createTime: '',
          modifyTime: '',
          deployTime: '',
          deploymentId: ''
        }
      })
    },
    handleAdd() {
      this.editModal = true
      this.action = 0
      nextTick(() => {
        this.clearCurrObj()
        this.doReset()
      })
    },
    handleDelete(rowIds) {
      this.modal_loading = true
      this.$api.request.workFlowDeploy
        .delete(rowIds)
        .then((res) => {
          this.modal_loading = false
          if (res) {
            this.$message.success(this.$i18n.t('messages.deleteSuccess') + '')
            this.handleSearch()
          }
        })
        .catch(() => {
          this.modal_loading = false
        })
    },
    handleSave(callBackFunc) {
      this.editForm.validate((valid) => {
        if (valid) {
          this.modal_loading = true
          switch (this.action) {
            case 0:
              this.$api.request.workFlowDeploy
                .create({
                  content: this.editFormModel.content,
                  remarks: this.editFormModel.remarks
                })
                .then((res) => {
                  this.modal_loading = false
                  if (res) {
                    if (typeof callBackFunc === 'function') {
                      callBackFunc()
                    } else {
                      this.$message.success(this.$i18n.t('messages.saveSuccess') + '')
                      this.editModal = false
                      this.handleSearch()
                    }
                  }
                })
                .catch(() => {
                  this.modal_loading = false
                })
              break
            case 1:
              this.modal_loading = true
              this.$api.request.workFlowDeploy
                .update({
                  id: this.editFormModel.id,
                  content: this.editFormModel.content,
                  remarks: this.editFormModel.remarks
                })
                .then((res) => {
                  this.modal_loading = false
                  if (res) {
                    if (typeof callBackFunc === 'function') {
                      callBackFunc()
                    } else {
                      this.$message.success(this.$i18n.t('messages.saveSuccess') + '')
                      this.editModal = false
                      this.handleSearch()
                    }
                  }
                })
                .catch(() => {
                  this.modal_loading = false
                })
              break
          }
        }
      })
    },
    handleDeploy() {
      this.$confirm(
        this.$i18n.t('messages.deployWorkFlowConfirm') + '',
        this.$i18n.t('dialog.confirm') + '',
        {
          type: 'warning'
        }
      )
        .then(() => {
          this.handleSave(() => {
            this.doDeploy()
          })
        })
        .catch(() => {})
    },
    doDeploy() {
      this.modal_loading = true
      this.$api.request.workFlowDeploy
        .deploy(this.editFormModel.id)
        .then((res) => {
          this.modal_loading = false
          if (res) {
            this.$message.success(this.$i18n.t('messages.requestSuccess') + '')
            this.editModal = false
            this.handleSearch()
          }
        })
        .catch(() => {
          this.modal_loading = false
        })
    },
    handlePageSizeSearch(size) {
      this.searchFormModel.pageSize = size
      this.handleSearch()
    },
    handleSearch() {
      let searchParam = {
        processKey: this.searchFormModel.processKey,
        name: this.searchFormModel.name,
        queryParam: {
          currPage: this.searchFormModel.currPage,
          pageSize: this.searchFormModel.pageSize
        }
      }
      if (this.searchFormModel.orderParam.order !== 'normal') {
        searchParam.queryParam.orderName = this.searchFormModel.orderParam.prop
        searchParam.queryParam.orderCommand = this.searchFormModel.orderParam.order
      }
      this.modal_loading = true
      this.$api.request.workFlowDeploy
        .query(searchParam)
        .then((res) => {
          this.modal_loading = false
          if (res) {
            this.selectedData = []
            this.searchFormModel.totalRows = res.data.page.totalElements
            this.searchData = []
            this.searchData = res.data.content
          }
        })
        .catch(() => {
          this.searchData = []
          this.selectedData = []
          this.modal_loading = false
        })
    },
    handleRowClick(row) {
      this.table.toggleRowSelection(row)
    },
    handleSortChange(param) {
      this.searchFormModel.orderParam.prop = param.prop
      this.searchFormModel.orderParam.order = param.order
      this.handleSearch()
    },
    handleSearchReset() {
      this.searchForm.resetFields()
    },
    handleSelect(selection) {
      this.selectedData = selection
    },
    handleDeleteRow(row) {
      this.$confirm(
        this.$i18n.t('messages.deleteDataConfirm') + '',
        this.$i18n.t('dialog.confirm') + '',
        {
          type: 'warning'
        }
      )
        .then(() => {
          this.handleDelete([row.id])
        })
        .catch(() => {})
    },
    handleDeleteMore() {
      if (this.selectedData.length > 0) {
        this.$confirm(
          this.$i18n.t('messages.deleteDataConfirm') + '',
          this.$i18n.t('dialog.confirm') + '',
          {
            type: 'warning'
          }
        )
          .then(() => {
            this.handleDelete(this.selectedData.map((item) => item.id))
          })
          .catch(() => {})
      } else {
        this.$alert(
          this.$i18n.t('messages.selectDataForDelete') + '',
          this.$i18n.t('dialog.info') + '',
          {
            type: 'error',
            callback: () => {}
          }
        )
      }
    },
    handleEdit(row) {
      this.editModal = true
      this.action = 1
      this.currObj = copy(row)
      nextTick(() => {
        this.doReset()
      })
    },
    handleEditBpmn() {
      this.bpmnView = true
      nextTick(() => {
        this.bpmn.doInitBpmn()
      })
    },
    handleUploadBpmn(file) {
      this.$api.getFileContent(file).then((res) => {
        if (res) {
          this.editFormModel.content = res.data
          this.handleEditBpmn()
        }
      })
    },
    handleBpmnChange(content) {
      this.editFormModel.content = content
      this.bpmnView = false
    },
    handleDownLoadFile() {
      this.$api.request.workFlowDeploy.downLoadFile(this.editFormModel.id)
    }
  },
  mounted() {
    this.handleSearch()
  },
  activated() {
    nextTick(() => {
      this.table.doLayout()
    })
  },
  setup() {
    const searchForm = ref(null)
    const table = ref(null)
    const editForm = ref(null)
    const bpmn = ref(null)
    return { searchForm, table, editForm, bpmn }
  }
}
</script>
